import wx


class Calculator(wx.Frame):
    def __init__(self, parent, title):
        super(Calculator, self).__init__(parent, title=title, size=(300, 400))

        # 创建面板和布局
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)

        # 创建文本输入框
        self.display = wx.TextCtrl(panel, style=wx.TE_RIGHT)
        sizer.Add(self.display, 0, wx.EXPAND | wx.ALL, 5)

        # 创建按钮网格
        buttons = [
            "7",
            "8",
            "9",
            "/",
            "4",
            "5",
            "6",
            "*",
            "1",
            "2",
            "3",
            "-",
            "0",
            ".",
            "=",
            "+",
        ]

        grid_sizer = wx.GridSizer(4, 4, 5, 5)
        for label in buttons:
            button = wx.Button(panel, label=label)
            button.Bind(wx.EVT_BUTTON, self.on_button_click)
            grid_sizer.Add(button, 0, wx.EXPAND)

        sizer.Add(grid_sizer, 1, wx.EXPAND | wx.ALL, 5)
        panel.SetSizer(sizer)

        self.Show()

    def on_button_click(self, event):
        button = event.GetEventObject()
        label = button.GetLabel()

        if label == "=":
            try:
                result = eval(self.display.GetValue())
                self.display.SetValue(str(result))
            except Exception:
                self.display.SetValue("Error")
        else:
            current_text = self.display.GetValue()
            self.display.SetValue(current_text + label)


if __name__ == "__main__":
    app = wx.App()
    frame = Calculator(None, "简易计算器")
    app.MainLoop()
